import styles from '../index.module.less';
import { historyEntrustFields } from '@/utils/helper';
import { useEffect, useRef, useState } from 'react';
import { ProTable, ProColumns } from '@ant-design/pro-components';
import FilterSelect from './FilterSelect';
import {
  tifTypes,
  isSuccess,
  orderStatusTypes,
  getOrderByUser,
  getUsdtNum,
  handleDirection,
  getUserDirectionNum,
} from '@/utils';
import { myHistoryOrderApi } from '@/api';
import dayjs from 'dayjs';

export default function HistoryEntrust({ tableWidth }: any) {
  const [list, setList] = useState<any>([]);
  const tableRef: any = useRef('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {}, []);

  // 历史订单
  async function getData(val: any) {
    console.log('val: ', val);
    const params: any = {
      ...val,
      status: 'open',
      contract: '',
    };
    console.log('params: ', params);
    setLoading(true);
    const res: any = await myHistoryOrderApi(params);
    setLoading(false);
    console.log('res: 历史委托: ', res?.data);
    if (!isSuccess(res)) return;
    setList(res?.data?.list);
  }

  const columns: ProColumns[] = [
    {
      title: '合约',
      dataIndex: 'contract',
    },
    {
      title: 'ID',
      dataIndex: 'gateid',
    },
    {
      title: '创建时间',
      dataIndex: 'geateCreateTime',
      width: 100,
      render: (text: any) => <>{dayjs(text * 1000).format('YYYY-MM-DD HH:mm:ss')}</>,
      hideInSearch: true,
    },
    {
      title: '结束时间',
      dataIndex: 'finish_time',
      width: 100,
      render: (text: any) => <>{dayjs(text * 1000).format('YYYY-MM-DD HH:mm:ss')}</>,
    },
    {
      title: '方向',
      dataIndex: 'newSize',
      render: (text: any, record: any) => (
        <p className={`${+text > 0 ? 'color-red' : 'color-green'}`}>
          {+text > 0 ? '做多' : '做空'}
          {record?.is_liq && '（强平）'}
        </p>
      ),
    },
    {
      title: '成交均价|委托价',
      dataIndex: 'fill_price',
      render: (text: any, record: any) => (
        <>
          {Number(text).toFixed(2)} <br />
          {record.price === '0' && record.tif === 'ioc' ? '市价' : record.price}
        </>
      ),
    },
    {
      title: '已成交|委托数量',
      dataIndex: 'size',
      render: (text: any, record: any) => (
        <>
          <div>
            {record?.finish_as === 'cancelled' && 0}
            {record?.finish_as === 'filled' && Math.abs(getUsdtNum(record))}
            &nbsp;USDT
          </div>
          <div>{Math.abs(getUsdtNum(record))} USDT</div>
        </>
      ),
    },
    {
      title: '平仓收益|收益率',
      dataIndex: 'pnl',
      render: (text: any, record: any) => (
        <>
          {text === '0' ? (
            '--'
          ) : (
            <div className={`${text * record?.userDirection > 0 ? 'color-red' : 'color-green'}`}>
              <div>{Number(text * record?.userDirection)?.toFixed(2)} USDT</div>
              <div>
                {Number(((text * record?.userDirection) / record?.pnl_margin) * 100)?.toFixed(2)}%
              </div>
            </div>
          )}
        </>
      ),
    },
    {
      title: '生效方式',
      dataIndex: 'tif',
      render: (text: any) => (
        <>
          {tifTypes[text]} <br />({text.toUpperCase()})
        </>
      ),
    },
    {
      title: '冰山委托(USDT)',
      dataIndex: 'iceberg',
      render: (text: any, record: any) => <>{text === 0 ? '-' : getUsdtNum(record, text)}</>,
    },
    {
      title: '只减仓',
      dataIndex: 'is_reduce_only',
      render: (text: any) => <>{text ? '是' : '否'}</>,
    },
    {
      title: '止盈/止损',
      dataIndex: 'takeProfitStopLoss',
    },
    {
      title: '订单状态',
      dataIndex: 'finish_as',
      render: (text: any) => <>{orderStatusTypes[text]}</>,
    },
    // {
    //   title: '来源',
    //   dataIndex: 'text',
    //   render: (text: any) => <>{sourceTypes(text)}</>,
    // },
  ];

  return (
    <>
      <FilterSelect fields={historyEntrustFields} reload={getData} isNomalTime={true} />
      <ProTable
        rowKey="id"
        columns={columns}
        dataSource={list}
        actionRef={tableRef}
        search={false}
        options={false}
        scroll={{ x: tableWidth }}
        // pagination={false}
        loading={loading}
      />
      <div className={`${styles.xxx} xxx`}></div>
    </>
  );
}
